#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash lapack-3.10.1.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1
if [[ "$1" == "$2" ]]; then echo "构建路径与安装路径不能相同，请输入正确的路径"; exit 1; fi

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
set -e
#yum install -y wget tar perl-Data-Dumper autoconf automake libtool numactl binutils systemd-devel valgrind flex environment-modules gcc-c++ git

download_pkg()
{
    wget -t 40 -c $1 -O $buildpath/lapack-3.10.1.tar.gz
    tar xf $buildpath/lapack-3.10.1.tar.gz -C $buildpath
    rm -rf $buildpath/lapack-3.10.1.tar.gz
}

download_pkg https://ghproxy.com/github.com/Reference-LAPACK/lapack/archive/refs/tags/v3.10.1.tar.gz
cd $buildpath/lapack-3.10.1
cp make.inc.example make.inc
sed -i -e '/^CC/s+gcc+clang+g' -e '/^FC/s+gfortran+flang+g' -e '/^TIMER = INT_ETIME/s+^+#+g' -e '/^#TIMER = INT_CPU_TIME/s+#++g' -e 's/librefblas.a/libblas.a/g' -e 's/-frecursive//g' make.inc
sed -i 's/lib: lapacklib tmglib/lib: blaslib variants lapacklib tmglib cblaslib blaspplib/g' Makefile
make -j$(nproc)
mkdir -p $installpath/lapack-3.10.1/lib
cp lib*.a $installpath/lapack-3.10.1/lib/

cat>"$installpath/lapack-3.10.1/lapack_modulefiles"<<EOF
#%Module1.0
conflict lapack
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set lapack [getModulefileDir]
setenv LAPACK \$lapack
prepend-path LD_LIBRARY_PATH \$lapack/lib
EOF

rm -rf $buildpath/lapack-3.10.1 
